from flask_socketio import SocketIO, emit
import threading
import time
from datetime import datetime

class MsgService:
    def __init__(self,socketio):
        self.socketio = socketio
        # 存储最新数据
        self.latest_data = {
            'realtime': None,
            'status': None,
            'events': []
        }
        # 锁用于线程安全
        self.data_lock = threading.Lock()
        
    def process_realtime_data(self, data):
        """处理实时数据"""
        with self.data_lock:
            self.latest_data['realtime'] = data
        # 广播到所有前端
        self.socketio.emit('ros_realtime_data', data)
        return {"code": 200, "message": "实时数据处理成功"}
    
    def process_status_data(self, data):
        """处理状态数据"""
        with self.data_lock:
            self.latest_data['status'] = data
            print("状态数据:")
            print(data)
            
        # 广播到所有前端
        self.socketio.emit('ros_status_data', data)
        return {"code": 200, "message": "状态数据处理成功"}
    
    def process_event_data(self, data):
        """处理事件数据"""
        with self.data_lock:
            # 根据事件类型分类存储
            event_type = data.get('type', 'unknown')
            print("事件数据")
            print(data)
            self.latest_data['events'].append(data)
            if len(self.latest_data['events']) > 100:
                self.latest_data['events'] = self.latest_data['events'][-100:]
                
        # 广播到所有前端
        self.socketio.emit('ros_event_data', data)
        return {"code": 200, "message": "事件数据处理成功"}
    